<?php

namespace App\Http\Responses\InsideMessage;

use App\Models\InsideMessage;
use App\Models\InsideMessageSystem;
use App\Services\InsideMessageService;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Database\Eloquent\Model;

class IndexResponse implements Responsable
{
    protected $result;

    protected $type;

    public function __construct($result, $type)
    {
        $this->result = $result;
        $this->type = $type;
    }

    public function toResponse($request)
    {
        return response_api($this->transform());
    }

    protected function transform()
    {
        $this->result->getCollection()->transform(function (Model $message) {
            return 0 === strcmp($this->type, InsideMessageService::SYSTEM_TYPE) ?
                $this->setSystemMessageList($message) :
                $this->setPointMessageList($message);
        });

        return $this->result;
    }

    /**
     * 点对点业务发送数据结构
     *
     * @param InsideMessage $message
     * @return array
     */
    protected function setPointMessageList(InsideMessage $message): array
    {
        return [
            'is_read'     => $message->state,
            'message_id'  => $message->id,
            'title'       => $message->insideMessageContent->title,
            'contact_way' => $message->insideMessageContent->contact_way,
            'content'     => $message->insideMessageContent->content,
            'created_at'  => $message->created_at->diffForHumans(),
        ];
    }

    /**
     * 系统群发数据结构
     *
     * @param InsideMessageSystem $message
     * @return array
     */
    protected function setSystemMessageList(InsideMessageSystem $message): array
    {
        return [
            'is_read'     => $message->state,
            'message_id'  => $message->insideMessageContents->id,
            'title'       => $message->insideMessageContents->insideMessageContent->title,
            'contact_way' => $message->insideMessageContents->insideMessageContent->contact_way,
            'content'     => $message->insideMessageContents->insideMessageContent->content,
            'created_at'  => $message->created_at->diffForHumans(),
        ];
    }
}